#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (C) 2004-2006 Vittorio Palmisano <vpalmisano at gmail dot com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
import os, sys, re

def __parse_xml(data):
	import xml.sax
	signal_list = []
	class GladeHandler(xml.sax.ContentHandler):
		#def startDocument(self): pass
		def startElement(self, tag, attributes):
			if tag == 'widget': 
				widget_list.append(attributes.get('id'))
			elif tag == 'signal': 
				signal_list.append(attributes.get('handler'))
		#def endDocument(self): pass
	p = xml.sax.make_parser()
	p.setContentHandler(GladeHandler())
	p.feed(data)
	p.close()
	return signal_list

def parse_xml(data):
	r = re.compile(r'<signal name=\".*?\" handler=\"(.*?)\"', re.M)
	signal_list = []
	for s in r.findall(data):
		signal_list.append(s)
	return signal_list

proto_locale = """APP='%(appName)s'
DIR='locale'

import locale
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
gettext.install(APP, DIR, unicode=1)

gtk.glade.bindtextdomain(APP, DIR)
gtk.glade.textdomain(APP)
"""

proto = """#!/usr/bin/env python
try:
	import pygtk
	pygtk.require('2.0')
except:
	pass
import gtk
import gtk.glade
import os
import sys
import gettext
%(proto_locale)s
def get_path(filename):
    if not os.path.isabs(filename):
        _dirname = os.path.dirname(os.path.abspath(__file__)) 
        return _dirname + os.path.sep + filename
    else:
        return filename

class GladeView(object):
    def __init__(self, filename, widget_name, signals={}):
        self._widgetTree = gtk.glade.XML(get_path(filename), widget_name, 
                                        gettext.textdomain())
        dic = {}
        for k in dir(signals):
            if k.startswith('on_'):
                dic[k] = getattr(signals, k)
        self._widgetTree.signal_autoconnect(dic)
	
    def __getattr__(self, name):
        if not name:
            return self.__dict__['_widgetTree']
        try:
            return self.__dict__['_widgetTree'].get_widget(name)
        except AttributeError:
            return getattr(self.__dict__['_widgetTree'], name)

class GladeControl:	
    %(handlers)s

class Application(GladeControl):
    def __init__(self):
        self.view = GladeView('%(gladeFile)s', '%(mainWindow)s', self)

if __name__ == '__main__':
    Application()
    gtk.main()
"""

proto_handler="""def %(hName)s(self, widget, *args):
        print '%(hName)s(widget=%%s, args=%%s)' %%(widget, args)
""" # %(signal_name, signal_name)

proto_makefile = """
all: GladeApplication.py

GladeApplication.py: ui.glade
	pyglade $<

clean:
	rm GladeApplication.py*
"""


if __name__=='__main__' :
    if(len(sys.argv) < 2):
        sys.exit(-1)
	
    data = open(sys.argv[1]).read()
    signal_list = parse_xml(data)

    handlers = "\n    ".join([proto_handler %{'hName': s} for s in signal_list])

    fileName = sys.argv[1].replace('.glade', '.py')
    appName = sys.argv[1].replace('.glade', '')
    gladeFile = os.path.basename(sys.argv[1])

    if len(sys.argv) == 3:
        mainWindow = sys.argv[2]
    else:
        r=re.compile('<widget class="GtkWindow" id="(.*?)"')
        mainWindow = r.findall(data)[0]

    out = open('GladeApplication.py', 'w')
    out.write(proto %{'handlers': handlers, 'gladeFile': gladeFile, 
        'mainWindow': mainWindow, 'appName': appName,
        'proto_locale': '',
        })
    out.close()
